//
//  GestureLoginVC.m
//  IDCardManager
//
//  Created by 金牛 on 2017/8/26.
//  Copyright © 2017年 zou. All rights reserved.
//

#import "GestureLoginVC.h"
#import "PCCircleView.h"
#import "PCLockLabel.h"
#import "PCCircleViewConst.h"
#import "PCCircleInfoView.h"
#import "PCCircle.h"
#import <AudioToolbox/AudioToolbox.h>
#import "NewTabbarVC.h"
#import <YZAuthID/YZAuthID.h>
@interface GestureLoginVC ()<CircleViewDelegate>
{
    PCLockLabel * _msgLab ;
    PCCircleInfoView * _infoView;
    UIImageView * _bgView;
    UILabel * _navTitleLab;
    UILabel *_label;
}
@property (nonatomic,strong) NSMutableArray *tabbarArr;
@end

@implementation GestureLoginVC

- (void)viewDidLoad {
    [super viewDidLoad];

    [self createInputGestureView];
    self.isHideNavBar = YES;
    NSDictionary *infoPlist = [[NSBundle mainBundle] infoDictionary];
    NSString *icon = [[infoPlist valueForKeyPath:@"CFBundleIcons.CFBundlePrimaryIcon.CFBundleIconFiles"] lastObject];
    UIImageView *imageView = [UIImageView new];
    imageView.image = Image(icon);
    imageView.cornerRadius = 5;
    [self.view addSubview:imageView];
    imageView.sd_layout.topSpaceToView(self.view, 80).centerXEqualToView(self.view).widthEqualToHeight().heightIs(80);
    _label = [UILabel labelWithTitle:@"请输入手势密码" color:[UIColor blackColor] fontSize:16 alignment:NSTextAlignmentCenter];
    [self.view addSubview:_label];
    _label.sd_layout.topSpaceToView(imageView, 30).leftSpaceToView(self.view, 0).rightSpaceToView(self.view, 0).heightIs(20);
}
-(void)createInputGestureView{
    _navTitleLab.text = @"输入解锁手势";
    _bgView = [[UIImageView alloc]initWithFrame:self.view.bounds];
    _bgView.userInteractionEnabled = YES;
    [self.view addSubview:_bgView];
    _bgView.image = Image(@"gesture_login");
    PCCircleView *lockView = [[PCCircleView alloc]initWithType:CircleViewTypeLogin clip:YES arrow:NO withCenterFloat:60];
    lockView.delegate = self;
    [_bgView addSubview:lockView];
    
    _msgLab = [[PCLockLabel alloc] init];
    _msgLab.frame = CGRectMake(0, 0, IPHONE_WIDTH, 14);
    _msgLab.center = CGPointMake(IPHONE_WIDTH/2, CGRectGetMinY(lockView.frame) - 30);
    [_bgView addSubview:_msgLab];
    
    UIButton * anBtn = [UIButton new];
    anBtn.titleLabel.font = UIFontMake(15);
    [anBtn setTitleColor:ThemeColor forState:UIControlStateNormal];
    anBtn.tag = 12;
    [anBtn setTitle:iPhoneX ? @"使用扫脸识别":@"使用指纹验证" forState:UIControlStateNormal];
    [anBtn addTarget:self action:@selector(forgetGesturePsw) forControlEvents:UIControlEventTouchUpInside];
    [_bgView addSubview:anBtn];
    anBtn.sd_layout.centerXEqualToView(_bgView).bottomSpaceToView(_bgView, KTabbarSafeBottomMargin + 30).heightIs(AUTO(30)).widthIs(AUTO(120));
}
-(void)forgetGesturePsw{
    [[YZAuthID alloc] yz_showAuthIDWithDescribe:nil block:^(YZAuthIDState state, NSError *error) {
        if (state == YZAuthIDStateNotSupport) {
            [QMUITips showError:@"对不起，当前设备不支持指纹/面部ID"];
        } else if(state == YZAuthIDStateFail) {
            [QMUITips showError:@"指纹/面部ID不正确，认证失败"];
        } else if(state == YZAuthIDStateTouchIDLockout) {
            [QMUITips showError:@"多次错误，指纹/面部ID已被锁定，请到手机解锁界面输入密码"];
        } else if (state == YZAuthIDStateSuccess) {
            NewTabbarVC * tab = [NewTabbarVC new];
            [UIApplication sharedApplication].delegate.window.rootViewController = tab;
        }
    }];
}
- (void)circleView:(PCCircleView *)view type:(CircleViewType)type connectCirclesLessThanNeedWithGesture:(NSString *)gesture{
    NSString *gestureOne = [PCCircleViewConst getGestureWithKey:gestureOneSaveKey];
    // 看是否存在第一个密码
    if ([gestureOne length]) {
        VLog(@"提示再次绘制之前绘制的第一个手势密码");
        [_msgLab showNormalMsg:@"请重复正确手势"];
    } else {
        VLog(@"密码长度不合法%@", gesture);
        [_msgLab showWarnMsg:@"请设置至少四个连线"];
    }
}
- (void)circleView:(PCCircleView *)view type:(CircleViewType)type didCompleteSetFirstGesture:(NSString *)gesture{
    VLog(@"获得第一个手势密码%@", gesture);
    // infoView展示对应选中的圆
    [_msgLab showNormalMsg:@"请重复手势"];
    [self infoViewSelectedSubviewsSameAsCircleView:view];
    
}

- (void)circleView:(PCCircleView *)view type:(CircleViewType)type didCompleteSetSecondGesture:(NSString *)gesture result:(BOOL)equal{
    VLog(@"获得第二个手势密码%@",gesture);
    if (equal) {
        VLog(@"两次手势匹配！可以进行本地化保存了");
        [self gotoTabBarView];
    } else {
        VLog(@"两次手势不匹配！");
        [_msgLab showWarnMsg:@"两次手势不匹配！"];
    }
}
-(void)gotoTabBarView{
    NewTabbarVC * tab = [NewTabbarVC new];
    [UIApplication sharedApplication].delegate.window.rootViewController = tab;
}
#pragma mark - circleView - delegate - login or verify gesture
- (void)circleView:(PCCircleView *)view type:(CircleViewType)type didCompleteLoginGesture:(NSString *)gesture result:(BOOL)equal{
    // 此时的type有两种情况 Login or verify
    if (type == CircleViewTypeLogin) {
        if (equal) {
            VLog(@"登陆成功！");
            [self gotoTabBarView];
        } else {
            [self shakeAnimationForView:_label];
            _label.text = @"密码错误";
            _label.textColor = [UIColor redColor];
        }
    } else if (type == CircleViewTypeVerify) {
        if (equal) {
            VLog(@"验证成功，跳转到设置手势界面");
        } else {
            VLog(@"原手势密码输入错误！");            
        }
    }
}
- (void)shakeAnimationForView:(UIView *) view
{
    CALayer *viewLayer = view.layer;
    CGPoint position = viewLayer.position;
    CGPoint x = CGPointMake(position.x + 10, position.y);
    CGPoint y = CGPointMake(position.x - 10, position.y);
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"position"];
    [animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
    [animation setFromValue:[NSValue valueWithCGPoint:x]];
    [animation setToValue:[NSValue valueWithCGPoint:y]];
    [animation setAutoreverses:YES];
    [animation setDuration:.06];
    [animation setRepeatCount:3];
    [viewLayer addAnimation:animation forKey:nil];
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}
#pragma mark - 让infoView对应按钮选中
- (void)infoViewSelectedSubviewsSameAsCircleView:(PCCircleView *)circleView {
    for (PCCircle *circle in circleView.subviews) {
        
        if (circle.circleState == CircleStateSelected || circle.circleState == CircleStateLastOneSelected) {
            
            for (PCCircle *infoCircle in _infoView.subviews) {
                if (infoCircle.tag == circle.tag) {
                    [infoCircle setCircleState:CircleStateSelected];
                }
            }
        }
    }
}
@end
